package dbAccess;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import constant.Constant;

public class MySQLAccess {
  private Connection connect = null;
  private Statement statement = null;
  private ResultSet resultSet = null;

  public MySQLAccess() throws Exception {
	  try {
		Class.forName("com.mysql.jdbc.Driver");
	
		 // setup the connection with the database, it use constant in the Constant.java
	      connect = DriverManager.getConnection(Constant.DATABASE_URL,Constant.DATABASE_USERNAME,Constant.DATABASE_PASSWORD);
		 
	} catch (Exception e) {
		throw e;
	}
}
  

  /**
   * Insert values into the database
 * @param table The table to used
 * @param values Values, must be formatted like the following example : (value 1, value 2, value 3)
 */
public void insertData(String table, String values){
	     // statements allow to issue SQL queries to the database
      try {
		statement = connect.createStatement();
		 // execute an insert into the database
	      statement.executeUpdate("insert into " + table + " values " + values + ";");
	   	} catch (SQLException e) {
		e.printStackTrace();
	}
  }
  
/**
 * Update a record
 * @param table The table to update
 * @param values values to update, must be formatted like the following example : values1='values1',values2='values2'
 * @param condition the condition to update example : values1='xxx' AND values2='yyy'
 */
public void updateData(String table, String values, String condition){
	     // statements allow to issue SQL queries to the database
   try {
		statement = connect.createStatement();
		 // execute an update into the database
	      statement.executeUpdate("update " + table + " set " + values + " where " + condition +";");
	   	} catch (SQLException e) {
		e.printStackTrace();
	}
}

/**
 * Remove a record from the database
 * @param table The table to update
 * @param condition The condition to remove records example : values1='xxx' AND values2='yyy'
 */
public void deleteData(String table, String condition){
    // statements allow to issue SQL queries to the database
try {
	statement = connect.createStatement();
	 // insert data
     statement.executeUpdate("delete from " + table + " where " + condition + ";");
  	} catch (SQLException e) {
	e.printStackTrace();
}
}
  

  /**
   * Select data from a database
 * @param table The database to select
 * @return The selected data into a resultSet
 */
public ResultSet selectData(String table) {
	
      // statements allow to issue SQL queries to the database
      try {
		statement = connect.createStatement();
		 // resultSet gets the result of the SQL query
	      resultSet = statement.executeQuery("select * from " + table);
	   	} catch (SQLException e) {
		e.printStackTrace();
	}
    
	return resultSet;
     

  }

  
} 